package com.shensi.adminCollect.util.markert;


import cn.hutool.core.util.DesensitizedUtil;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.redis.service.RedisCache;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.LocalDateTimeUtil;
import com.shensi.adminCollect.domain.markert.SaleActivityOrder;
import com.shensi.adminCollect.domain.station.Station;
import com.shensi.adminCollect.domain.station.StationDeviceManage;
import com.shensi.adminCollect.enums.station.PrintEnum;
import com.shensi.adminCollect.service.station.IStationDeviceManageService;
import com.shensi.adminCollect.service.station.IStationService;
import com.shensi.adminCollect.utils.station.FeiEPrinterUtil;
import com.shensi.adminCollect.utils.station.Methods;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @date 2023/12/27
 */
@Component
public class PrintUtil {

    private static final Logger log = LoggerFactory.getLogger(PrintUtil.class);
    @Autowired
    private IStationDeviceManageService stationDeviceManageService;
    @Autowired
    private IStationService stationService;
    @Autowired
    private RedisCache redisCache;

    @Async("threadPoolTaskExecutor")
    public void printRefundSaleOrder(SaleActivityOrder activityOrder) {

        StationDeviceManage stationDeviceManage = getStationDeviceManage(activityOrder.getStationId().toString());
        if(stationDeviceManage.getIsPrint() == 0){
            return;
        }
        String refundPrintContent = getRefundSaleOrderContent(activityOrder,stationDeviceManage);
        printOrder(stationDeviceManage, refundPrintContent);

    }

    private void printOrder(StationDeviceManage stationDeviceManage, String content){
        log.info("小票机信息【{}】", stationDeviceManage);
        String deviceFactory = stationDeviceManage.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);

        String printRes = "";
        AjaxResult ajaxResult = AjaxResult.success();
        switch (printEnum){
            case YILIANYUNK4:

                Integer random6K4 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods mK4= Methods.getInstance();
                Object tokenK4 = redisCache.getCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId());
                log.info("token:{}",tokenK4);
                if(Objects.nonNull(tokenK4)){
                    String print = mK4.print(stationDeviceManage.getClientId(),stationDeviceManage.getDeviceNo(), content, random6K4.toString(), tokenK4.toString());
                    log.info("小票机返回值{}",print);
                    org.json.JSONObject json = new org.json.JSONObject(print);
                    if("0".equals(json.getString("error"))){
                        break;
                    }
                }

                //初始化终端信息
                mK4.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
                //获取token
                String refreshTokenK4 = mK4.getFreedomToken();
                log.info("新的token{}",refreshTokenK4);
                //存入redis
                redisCache.setCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId(),refreshTokenK4,30, TimeUnit.DAYS);


                String printK4 = mK4.print(stationDeviceManage.getDeviceNo(), content, random6K4.toString());
                log.info("小票机返回值2{}",printK4);

                break;

            case YILIANYUN:
                Integer random6 = (int) ((Math.random() * 9 + 1) * 100000);
                //初始化控制器类
                Methods m= Methods.getInstance();
                Object token = redisCache.getCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId());
                log.info("token:{}",token);
                if(Objects.nonNull(token)){
                    String print = m.print(stationDeviceManage.getClientId(),stationDeviceManage.getDeviceNo(), content, random6.toString(), token.toString());
                    log.info("小票机返回值{}",print);
                    org.json.JSONObject json = new org.json.JSONObject(print);
                    if("0".equals(json.getString("error"))){
                        break;
                    }
                }

                //初始化终端信息
                m.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
                //获取token
                String refreshToken = m.getFreedomToken();
                log.info("新的token{}",refreshToken);
                //存入redis
                redisCache.setCacheObject("STATION:DEVICE:" + stationDeviceManage.getClientId(),refreshToken,30, TimeUnit.DAYS);


                String print = m.print(stationDeviceManage.getDeviceNo(), content, random6.toString());
                log.info("小票机返回值2{}",print);
                break;
            case FEIE:
                String result = FeiEPrinterUtil.printReceipt(stationDeviceManage.getDeviceNo(), content.toString());
                org.json.JSONObject resJson = new org.json.JSONObject(result);
                if("ok".equals(resJson.get("msg"))){
                    printRes = "补打小票成功";
                    ajaxResult = AjaxResult.success(printRes);
                }else {
                    printRes = "补打小票失败";
                    ajaxResult = AjaxResult.error(printRes);
                }

                break;
            default:
                log.info("没有配置小票机，打印失败");
                break;
        }
    }

    private String getRefundSaleOrderContent(SaleActivityOrder activityOrder,StationDeviceManage stationDeviceManage){
        log.info("退款打印小票,退款订单[{}]", activityOrder);
        StringBuilder content = new StringBuilder();
        String deviceFactory = stationDeviceManage.getDeviceFactory();
        PrintEnum printEnum = PrintEnum.getByCode(deviceFactory);
        log.info("小票机类型[{}]", printEnum);
        Station station = stationService.selectStationById(activityOrder.getStationId());
        String stationName = station == null ? activityOrder.getStationName() : station.getStationName();
        switch (printEnum){
            case YILIANYUNK4:
                content.append("<FS2><center>").append(stationName).append("</center></FS2>\r\n");
                content.append("<center>【秒杀退款】</center>\r\n");
                break;
            case YILIANYUN:
                content.append("<FS2><center>").append(stationName).append("</center></FS2>\r\n");
                content.append("<center>【秒杀退款】</center>\r\n");
                break;
            case FEIE:
                content.append("<BOLD><C><B>").append(stationName).append("</B></C></BOLD>\r\n");
                content.append("<C>【秒杀退款】</C>\r\n");
                break;
        }
        content.append("--------------------------------")
                .append("\r\n订单编号：").append(activityOrder.getOrderNo())
                .append("\r\n手机号：").append(DesensitizedUtil.mobilePhone(activityOrder.getMobilePhone()))
                .append("\r\n");
        switch (printEnum){
            case YILIANYUNK4:
                content.append("退款金额：<FS>").append(activityOrder.getAmt()).append("元</FS>\r\n");
                break;
            case YILIANYUN:
                content.append("退款金额：<FS>").append(activityOrder.getAmt()).append("元</FS>\r\n");
                break;
            case FEIE:
                content.append("<BOLD>退款金额：").append(activityOrder.getAmt()).append("元</BOLD>\n");
                break;
        }
        content.append("\r\n退款时间：").append(LocalDateTimeUtil.parse(activityOrder.getRefundTime()))
                .append("\r\n--------------------------------")
                .append("\r\n打印时间：").append(LocalDateTimeUtil.parse(LocalDateTime.now()))
                .append("\r\n")
                .append("谢谢惠顾！欢迎下次再来~")
                .append("\r\n")
                .append("\r\n")
                .append("\r\n");
        return content.toString();
    }

    private StationDeviceManage getStationDeviceManage(String stationId){
        log.info("打印退款小票");
        StationDeviceManage stationDeviceManager=new StationDeviceManage();
        stationDeviceManager.setStationId(Long.valueOf(stationId));
        stationDeviceManager.setDeviceType("3");
        List<StationDeviceManage> stationDeviceManages = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManager);
        if(CollectionUtils.isEmpty(stationDeviceManages)){
            throw new CustomException("当前油站没有配置小票机");
        }
        return stationDeviceManages.get(0);
    }

}
